# 公司id、名称映射
import re
import traceback
from datetime import datetime, timedelta

from db.entity import MatchData

company_id_names = [{
    "id": 115,
    "name": "威廉希尔"
}, {
    "id": 82,
    "name": "立博"
}, {
    "id": 281,
    "name": "_365"
}, {
    "id": 177,
    "name": "Pinnacle"
}, {
    "id": 80,
    "name": "澳门"
}]


def build_match_data(_match_id: str, _007match_js_str: str) -> MatchData:
    _match_record = MatchData()

    # _match_record.日期 = '2025-09-13 00:00:00'


    try:
        _id = _007match_js_str.split("ScheduleID=")[1].split(";")[0]
        _match_record.id = _id
        # "ScheduleID = 2722859;"
    except Exception as e:
        traceback.print_exc()
        print(f"时间解析错误: {str(e)}")

    try:
        # 2025,06-1,16,08,00,00
        time_str = _007match_js_str.split("MatchTime=")[1].split("\"")[1]
        time_parts = time_str.split(",")
        if len(time_parts) >= 6:
            # 月特殊处理
            month = time_parts[1].replace('-1', '')
            dt_str = f"{time_parts[0]}-{month}-{time_parts[2]} {time_parts[3]}:{time_parts[4]}:{time_parts[5]}"
            # 北京时间+8
            match_time = datetime.strptime(dt_str, "%Y-%m-%d %H:%M:%S") + timedelta(hours=8)
            # row_data[1] = match_time.strftime("%Y-%m-%d %H:%M:%S")
            _match_record.日期 = match_time.strftime("%Y-%m-%d %H:%M:%S")
    except Exception as e:
        traceback.print_exc()
        print(f"时间解析错误: {str(e)}")

    # 提取赛事名称 (对应VBA中的arr1(k, 3))
    try:
        league_name = _007match_js_str.split("matchname_cn=")[1].split("\"")[1]
        # row_data[2] = league_name
        _match_record.联赛 = league_name
    except:
        print(f"比赛id[{_match_id}] 赛事名称解析错误")
        traceback.print_exc()
        pass

    # 提取主队信息 (对应VBA中的arr1(k, 4-5))
    try:
        home_order = _007match_js_str.split("hOrder=")[1].split("\"")[1]
        home_team = _007match_js_str.split("hometeam_cn")[1].split("\"")[1]
        # row_data[3] = home_order
        # row_data[4] = home_team
        _match_record.主队 = home_team
        _match_record.主队排名 = home_order
    except:
        print(f"比赛id[{_match_id}] 主队信息解析错误")
        traceback.print_exc()
        pass

    # 提取客队信息 (对应VBA中的arr1(k, 8-9))
    try:
        away_team = _007match_js_str.split("guestteam_cn")[1].split("\"")[1]
        away_order = _007match_js_str.split("gOrder=")[1].split("\"")[1]

        # row_data[7] = away_team
        # row_data[8] = away_order
        _match_record.客队 = away_team
        _match_record.客队排名 = away_order
    except:
        print(f"比赛id[{_match_id}] 客队信息解析错误")
        traceback.print_exc()
        pass

    # 提取赛季信息 (对应VBA中的arr1(k, 11))
    try:
        season = _007match_js_str.split(" season=")[1].split("\"")[1]
        # row_data[10] = season
        _match_record.赛季 = season
    except:
        print(f"比赛id[{_match_id}] 赛季信息解析错误")
        traceback.print_exc()
        pass

    try:
        # 提取主队比分和客队比分
        home_score = _007match_js_str.split("homeScore=")[1].split("\"")[1]
        away_score = _007match_js_str.split("awayScore=")[1].split("\"")[1]
        _match_record.主队比分 = home_score
        _match_record.客队比分 = away_score
    except Exception as e:
        traceback.print_exc()
        print(f"比分解析错误: {str(e)}")

    try:
        # 提取半场比分
        half_time_score = _007match_js_str.split("halfTimeScore=")[1].split("\"")[1]
        _match_record.半场比分 = half_time_score
    except Exception as e:
        traceback.print_exc()
        print(f"半场比分解析错误: {str(e)}")

    try:
        # 提取赛果
        match_result = _007match_js_str.split("matchResult=")[1].split("\"")[1]
        _match_record.赛果 = match_result
    except Exception as e:
        traceback.print_exc()
        print(f"赛果解析错误: {str(e)}")

    try:
        # 提取进球数
        total_goals = _007match_js_str.split("totalGoals=")[1].split("\"")[1]
        _match_record.进球数 = total_goals
    except Exception as e:
        traceback.print_exc()
        print(f"进球数解析错误: {str(e)}")

    return _match_record


import requests
from bs4 import BeautifulSoup
import pandas as pd


def convert_fractional_goals(goals_str):
    """
    将分数形式的进球数转换为小数形式
    例如: "1.5/2" -> "1.75", "3.5/4" -> "3.75"

    参数:
    goals_str: 进球数字符串，可能是分数形式如"1.5/2"或普通数字如"2"

    返回:
    转换后的进球数字符串
    """
    if not goals_str:
        return goals_str

    # 如果包含"/"，说明是分数形式
    if "/" in goals_str:
        parts = goals_str.split("/")
        if len(parts) == 2:
            try:
                # 将两个数值转换为浮点数并求平均值
                first_value = float(parts[0])
                second_value = float(parts[1])
                average_value = (first_value + second_value) / 2
                # 如果结果是整数，返回整数形式，否则保留一位小数
                if average_value.is_integer():
                    return str(int(average_value))
                else:
                    return str(average_value)
            except ValueError:
                # 如果转换失败，返回原始字符串
                return goals_str
        else:
            return goals_str
    else:
        # 不是分数形式，直接返回
        return goals_str


def extract_over_under_odds(html_content):
    """
    从HTML内容中提取大小球指数数据

    参数:
    html_content: 包含大小球指数数据的HTML内容

    返回:
    DataFrame: 包含所有公司的大小球指数数据
    """
    # 使用BeautifulSoup解析HTML
    soup = BeautifulSoup(html_content, 'html.parser')

    # 找到包含大小球指数的表格
    table = soup.find('table', {'id': 'odds'})

    # 提取所有行
    rows = table.find_all('tr')

    # 准备存储数据的列表
    data = []

    # 遍历每一行
    for row in rows:
        # 跳过表头行
        if 'thead2' in row.get('class', []):
            continue

        # 提取公司名称和ID
        # 公司名称在第二个td中，公司ID在第三个td的span标签中
        tds = row.find_all('td')
        if len(tds) < 12:
            continue

        # 获取公司ID - 在第三个td中的span标签中
        company_id_cell = tds[2] if len(tds) > 2 else None
        company_id = None
        if company_id_cell:
            company_span = company_id_cell.find('span')
            if company_span and company_span.get('companyID'):
                company_id = company_span.get('companyID')
            elif company_span and company_span.get('companyid'):  # 兼容小写
                company_id = company_span.get('companyid')

        print(company_id)

        if company_id is None:
            # 是多盘数据
            continue

        # 提取所有数据单元格
        cells = row.find_all('td')

        # 确保有足够的单元格
        if len(cells) < 12:
            continue

        # 提取初盘数据
        initial_over = cells[3].get_text(strip=True)
        initial_goals = cells[4].get('goals', '')
        # 如果没有goals属性，则直接获取文本内容
        if not initial_goals:
            initial_goals = cells[4].get_text(strip=True)
        initial_under = cells[5].get_text(strip=True)

        real_time_over = cells[6].get_text(strip=True)
        real_time_goals = cells[7].get('goals', '') if cells[10].get('goals') else cells[10].get_text(strip=True)
        real_time_under = cells[8].get_text(strip=True)
        # 即时数据（如果结束了就等同于终盘）
        # 提取终盘数据
        final_over = cells[9].get_text(strip=True)
        final_goals = cells[10].get('goals', '') if cells[10].get('goals') else cells[10].get_text(strip=True)
        final_under = cells[11].get_text(strip=True)

        # 处理分数形式的进球数
        initial_goals = convert_fractional_goals(initial_goals)
        final_goals = convert_fractional_goals(final_goals)

        # 添加到数据列表
        data.append({
            '公司': company_id,
            '初盘大球': initial_over,
            '初盘进球数': initial_goals,
            '初盘小球': initial_under,

            '即时大球': real_time_over,
            '即时进球数': real_time_goals,
            '即时小球': real_time_under,

            '终盘大球': final_over,
            '终盘进球数': final_goals,
            '终盘小球': final_under
        })

    # 创建DataFrame
    df = pd.DataFrame(data)
    return df


def build_match_bf_data_list(response_text):
    """
    从bfdata.js格式的响应文本中解析A、B、C数组，并转换为比赛数据列表
    
    Args:
        response_text: bfdata.js文件的内容
        
    Returns:
        list: MatchData对象列表
    """
    # 提取JavaScript中的A、B、C数组定义
    import re


    # 使用正则表达式提取数组内容
    a_pattern = r'A\[(\d+)\] = "([^"]*)"\.split\("\^"\);'
    b_pattern = r'B\[(\d+)\] = "([^"]*)"\.split\("\^"\);'
    c_pattern = r'C\[(\d+)\] = \[(.*?)\];'
    
    # 初始化数组
    max_a = 169  # 根据bfdata.js中的定义
    max_b = 63   # 根据bfdata.js中的定义
    max_c = 43   # 根据bfdata.js中的定义
    
    A = [None] * max_a
    B = [None] * max_b
    C = [None] * max_c
    
    # 提取A数组
    for match in re.finditer(a_pattern, response_text):
        index = int(match.group(1))
        data = match.group(2).split('^')
        A[index] = data
    
    # 提取B数组
    for match in re.finditer(b_pattern, response_text):
        index = int(match.group(1))
        data = match.group(2).split('^')
        B[index] = data
    
    # 提取C数组
    for match in re.finditer(c_pattern, response_text):
        index = int(match.group(1))
        # 解析类似 52, '国际赛事', 0, '國際賽事', 0 的内容
        content = match.group(2)
        parts = content.split(',')
        if len(parts) >= 5:
            try:
                C[index] = [
                    int(parts[0].strip()),
                    parts[1].strip().strip("'"),
                    int(parts[2].strip()),
                    parts[3].strip().strip("'"),
                    int(parts[4].strip())
                ]
            except ValueError:
                # 如果转换失败，保持为None
                pass
    
    # 使用match_parser解析数据
    parser = parse_match_data_with_arrays(A, B, C)
    matches = parser.get_all_matches()
    
    # 转换为MatchData对象列表
    match_data_list = []
    for i, match_info in enumerate(matches, 1):
        match_data = MatchData()
        match_data.序号 = i
        match_data.id = match_info.get('match_id', '')
        match_data.日期 = match_info.get('match_time', '')
        match_data.联赛 = match_info.get('league_name', '')
        match_data.主队排名 = match_info.get('home_team', '')
        match_data.主队 = match_info.get('home_team', '')
        match_data.主队比分 = match_info.get('home_score', '')
        match_data.客队比分 = match_info.get('away_score', '')
        match_data.客队 = match_info.get('away_team', '')
        match_data.客队排名 = match_info.get('away_team', '')
        match_data.半场比分 = f"{match_info.get('home_half_score', '')}-{match_info.get('away_half_score', '')}"
        match_data.赛季 = ''  # bfdata.js中未提供赛季信息
        match_data.进球数 = ''  # bfdata.js中未直接提供进球数
        match_data.赛果 = ''  # bfdata.js中未直接提供赛果
        match_data.编号 = match_info.get('match_id', '')
        
        match_data_list.append(match_data)
    
    return match_data_list

def extra_jinqiu_data(match_id, response_text):
    return extract_over_under_odds(response_text)


def extra_yarang_data(match_id, response_text):
    return extract_over_under_odds(response_text)


# 使用示例
if __name__ == "__main__":
    # # 假设html_content是提供的HTML内容
    # # 这里应该是从文件或网络请求获取的HTML内容
    # with open('html/进球数.html', 'r', encoding='utf8') as f:

    with open('html/亚让.html', 'r', encoding='utf8') as f:
        html_content = f.read()

    # 提取数据+
    df = extract_over_under_odds(html_content)

    # 打印结果
    print(df)
